<template>
	<view>
		<!-- 规格弹窗 -->
		<uni-popup ref="popup" @maskClick='maskClickFun'> 
			<view class="pop-spece-view">
				<view class="chxy-row-c-c spece-select-desc">规格选择</view>
				<view class="h-20"></view>
				<view v-if="specsModal.priceList">
					<view>{{specsModal.goodsName}}</view>
					<view class="h-20"></view>
					<!-- 都是单选 -->
					<view class="spece-select-sig">
						<view v-for="(priceitem,priceindex) in specsModal.priceList" :key="priceindex + priceitem">
							<view @click="priceCheck(priceitem,priceindex)" :class="priceitem.check? 'specs-price-check':'specs-price-checkNo'" >
								{{priceitem.uomName }}
							</view>
						</view>
					</view>
				</view>
				<view class="h-40"></view>
				<view>
					<view v-for="(gooditem,goodindex) in specsModal.goodsFlavor" :key="goodindex + gooditem">
						<view>{{gooditem.Name}}</view>
						<view class="h-20"></view>
						<view>
							<!-- 0单选  -->
							<view  v-if="gooditem.IsMultiple === '0'" class="spece-gfla-sel">
								<view  @click="flaCheck(goodindex,findex)"  v-for="(fitem,findex) in gooditem.FlavorStr" :key="findex + fitem">
									<view :class="gooditem.defCheck.includes(fitem) ? 'specs-price-check':'specs-price-checkNo'">{{fitem}}</view>
								</view>
							</view>
							<!-- 1多选 -->
							<view  v-if="gooditem.IsMultiple === '1'" class="spece-gfla-sel">
								<view  @click="flaCheckMore(goodindex,findex,gooditem.defCheck.includes(fitem))"  v-for="(fitem,findex) in gooditem.FlavorStr" :key="findex + fitem">
									<view :class="gooditem.defCheck.includes(fitem) ? 'specs-price-check':'specs-price-checkNo'">{{fitem}}</view>
								</view>
							</view>
							<view class="h-20"></view>
						</view>
					</view>
				</view>
				
				<view v-if="specsModal.goodsFlavor">
					<view class="h-40"></view>
					已选规格: {{filterSpecs(specsModal.goodsFlavor)}}
					<view class="h-40"></view>
				</view>
				
				<view class="chxy-row-bt">
					<view class="price-text">
					    ￥{{specsPriceShower() }}
					</view> 
					<view style="margin-right: 50rpx;">
						<order-number-box :max="9999999" :min="1" v-model='specsModal.qty' />
					</view>
				</view>
				<view class="h-40"></view>
				<view>
					<view @tap="$u.throttle(handleSave, 500)" class="spece-add-bnt" >
						加入
					</view>
				</view>

			</view> 
		</uni-popup> 
	</view>
</template>

<script setup>
	import { ref, defineProps, defineEmits, defineExpose } from 'vue';
    import { numMultiFun } from '../../until/tools';
	
	const props = defineProps({
		handleFlag: {
			type: Boolean, 
			default: true
		},
	}); 
	
	const popup = ref( )  // 弹窗
	const showSpecs = ref(false) // 规格弹窗
	const specsModal = ref({}) // 规格对象
	const specsModalOldNum = ref(0) // 旧的规格数量 
	
	
	// 关闭蒙层需要恢复数量
	const maskClickFun = ( ) => {
		specsModal.value.qty = specsModalOldNum.value
	}
	
	// 初始化规格 - 需要配合maskClickFun >>> 要改成specsModal.value ==={...sModal}
	const initDataSpecs = (sModal) => {
		specsModalOldNum.value = { ...sModal}.qty
		console.log('initDataSpecs:', specsModalOldNum.value)
		sModal.qty = 1// 默认1
		sModal.priceList.forEach((item,index)=>{
			if(index === 0){
				sModal.priceList[index]['check'] = true // 默认选择第一个
			}else{
				sModal.priceList[index]['check'] = false  
			} 
		}) 
		try {
			sModal.goodsFlavor = filterChaosData(sModal.goodsFlavor)
		} catch (e) {
			// 临时默认第一个 后面调整
			if(sModal.goodsFlavor){
				sModal.goodsFlavor.forEach((item,index)=>{
					item['defCheck'] = [item.FlavorStr[0]]
					// item.FlavorStr.forEach((ditem,dindex)=>{ 
					// })
				})
			}
		}  
		specsModal.value = sModal
		console.log('initDataSpecs2：',specsModal.value)
		// showSpecs.value = true
		popup.value.open('center')  
	}
	
	// 显示规格商品的价格
	const specsPriceShower = () => { 
		let result = 0
		specsModal.value.priceList.forEach((item,index)=>{
			if(item.check){
				result = item.salePrice 
			} 
		})  
		return result
	}
 
	// priceCheck - 单选 （杯瓶等单位）
	const priceCheck = (cheitem,cheindex) => { 
		specsModal.value.priceList.forEach((item,index)=>{
			if(cheindex === index){
				item.check = true
				// specsModal.value.priceList[index].check  = true
			}else{
				item.check = false
			}
		}) 
	} 
	
	// flaCheck - 单选 （口味）
	const flaCheck = (goodindex,findex) => {
		specsModal.value.goodsFlavor[goodindex].FlavorStr.forEach((item,index)=>{ 
			if(index === findex){
				specsModal.value.goodsFlavor[goodindex].defCheck = [item]
			} 
		})
		console.log('specsModal.value.goodsFlavor[goodindex]:',specsModal.value.goodsFlavor[goodindex]) 
	}   
	
	// flaCheck - 多选（口味）
	const flaCheckMore = (goodindex,findex,checkFlag) => {
		let nowList = specsModal.value.goodsFlavor[goodindex]
		nowList.FlavorStr.forEach((item,index)=>{
			if(index === findex && !checkFlag){ 
				nowList.defCheck.push(item)
			}else if(index === findex && checkFlag){ 
				// 将item从nowList.defCheck移除  
				nowList.defCheck = nowList.defCheck.filter(checkItem => checkItem !== item); 
			}
		}) 
	}   
	
	const filterSpecs = (goodsFlavorList) => {
		return goodsFlavorList.flatMap(item => item.defCheck).join(','); 
	} 

	// 加入购物车 保存数据并 关闭弹窗 覆盖并累加qty值
	const handleSave = () => { 
		if(!props.handleFlag){
			uni.showToast({ title: '请先扫描桌台二维码后再继续下单', icon: 'none' })
			popup.value.close() 
			return
		} 
		// 不同规格做处理：此处特殊业务specsOthList存储 >>>相同的合并，不相同的push
		if(specsModal.value['specsOthList']){
			let nowPackage = JSON.parse(JSON.stringify(specsModal.value)) 
			let flag = true
			specsModal.value.specsOthList.forEach((item,index)=>{
				if( JSON.stringify(item.priceList) ===  JSON.stringify(specsModal.value.priceList) && JSON.stringify(item.goodsFlavor) === JSON.stringify(specsModal.value.goodsFlavor)){
					specsModal.value.qty = Number(nowPackage.qty)  + Number(specsModalOldNum.value)
					specsModal.value.specsOthList[index].qty += Number(nowPackage.qty)
					flag = false
				} 
			}) 
			if(flag){
				specsModal.value['specsOthList'].push(nowPackage)
				specsModal.value.qty = Number(nowPackage.qty)  + Number(specsModalOldNum.value)
			}  
		}else{
			let nowPackage = JSON.parse(JSON.stringify(specsModal.value))
			specsModal.value['specsOthList'] = []
			specsModal.value['specsOthList'].push(nowPackage)  
			specsModal.value.qty = Number(nowPackage.qty) 
		}
		console.log('specsModal.value:',specsModal.value)
		// specsModal.value.qty += specsModalOldNum.value
		// 跟新数据调整 
		emit('updateSpecsData', specsModal.value);
		// showSpecs.value = false
		popup.value.close() 
	}

	// 定义触发事件
	const emit = defineEmits(['updateSpecsData']);
	// 关闭弹窗 修复取消的qty值
	const handleClose = () => {
		specsModal.value.qty = specsModalOldNum.value
		// showSpecs.value = false
		popup.value.close() 
	};


	// 过滤数据 口味数据
	const filterChaosData = (val) => {
		let newList = JSON.parse(val)
		// console.log('subitem.goodsFlavor未调整前：',newList[0].FlavorStr) 
		newList.forEach((bigitem, bigindex) => {
			bigitem.FlavorStr = bigitem.FlavorStr.split(',');
			bigitem['defCheck'] = []
			bigitem.FlavorStr.forEach((item, index) => {
				if (item.includes('#')) {
					item = item.replace('#', '');
					bigitem['defCheck'].push(item)
					bigitem.FlavorStr[index] = item
				}
			})
		})
		return newList
	}

	defineExpose({
		initDataSpecs
	});
</script>

<style scoped lang="scss">
	
	.pop-spece-view{
		width: 634rpx;
		max-height: 70vh;
		padding: 24rpx;
		background-color: #fff;
		border-radius: 20rpx;
	}
	
	.spece-select-desc{
		font-size: 36rpx;
		font-weight: 600;
	}
	
	.spece-select-sig{
		display: flex;
		flex-wrap: wrap;
		gap: 5rpx;
		width: 654rpx;
	} 
	
	.spece-add-bnt{
	    width: 100%;
		background-color:var(--dt-backcolorPink);
		color: var(--maincolor);
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 50rpx;
		font-size: 32rpx;
	}
	
	.specs-price-check{
		height: 30rpx;
		padding: 6rpx 20rpx;
		line-height: 30rpx;
		font-size: 22rpx;
		border-radius: 10rpx;
		background-color: var(--dt-backcolorPink);
		color: var(--maincolor);
		margin-right: 20rpx;
	}
	
	.specs-price-checkNo{
		height: 30rpx;
		padding: 6rpx 20rpx;
		line-height: 30rpx;
		font-size: 22rpx;
		border-radius: 10rpx;
		background-color: var(--mainbaccolor2);
		color: var(--mainbaccolor7); 
		margin-right: 20rpx;
	}
	
	.spece-gfla-sel{
		display: flex; 
		flex-wrap: wrap; 
		gap: 5rpx;
		width: 654rpx;
	}
	
	.price-text {
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 44rpx;
		color: var(--maincolorf1);
	}
	
</style>